package cn.maihe.elg.operation.supports.bank.cmb.tradingmanager.utils;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version V1.0
 * @author: Sidon
 * @createTime: 2021-06-03 16:41
 * Copyright (C)2021-2021 福建省金柠网络科技有限公司. All rights reserved.
 */

public class CommonUtil {


    /**
     * 获取文件对应的Base64数据
     *
     * @param path 文件路径
     * @return path为空则返回空字符串，反之返回Base64编码
     */
    public static String getImageBase64(String path) {
        boolean empty = isEmpty(path);
        if (empty) {
            return "";
        }
        File file = new File(path);
        byte[] content = new byte[(int) file.length()];
        try (FileInputStream inputStream = new FileInputStream(file)) {
            inputStream.read(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(content);
    }

    /**
     * 判断Json字符串是否为空
     *
     * @param object 参数
     * @return 判断结果
     */
    public static boolean isJsonEmpty(Object object) {
        final boolean empty = isEmpty(object);
        if (!empty) {
            return "{}".equals(object.toString().replaceAll("[ \n\r]", ""));
        }
        return true;
    }

    /**
     * 判断对象是否为空
     *
     * @param object 参数
     * @return 判断结果
     */
    public static boolean isEmpty(Object object) {
        return object == null || "".equals(object) || "".equals(object.toString());
    }


    /**
     * 判断对象是否为空
     *
     * @param object 参数
     * @param def    默认值
     * @return 如果为true 则返回 def值，否则返回入参
     */
    public static String isEmpty(Object object, String def) {
        return object == null || "".equals(object) || "".equals(object.toString()) ? def : object.toString();
    }

    /**
     * 判断对象是否为非空
     *
     * @param object 参数
     * @return 判断结果
     */
    public static boolean isNotEmpty(Object object) {
        return !isEmpty(object);
    }

    /**
     * 判断对象内所有数据是否为非空
     *
     * @param object 参数
     * @return 判断结果
     */
    public static boolean isNotEmpty(Object... object) {
        int count = 0;
        for (Object obj : object) {
            if (isEmpty(obj)) {
                ++count;
            }
        }
        return count == object.length;
    }

    /**
     * 拼接字符串
     *
     * @param strings 字符串
     * @return 拼接结果
     */
    public static String stringAppend(Object... strings) {
        StringBuilder msg = new StringBuilder();
        for (Object string : strings) {
            msg.append(string);
        }
        return msg.toString();
    }

    /**
     * 判断对象是否为非空
     *
     * @param json json字符串
     * @return 判断结果
     */
    public static JSONObject isJson(String json) {
        try {
            return JSONObject.parseObject(json);
        } catch (Exception e) {
            return null;
        }
    }






    /**
     * 根据身份证计算年龄，计算的是周岁。每过一次生日年龄+1
     *
     * @param idCard 身份证号码，15或18位
     * @return 身份证年龄,-1为身份证计算错误
     */
    public static int calculateByIdCard(String idCard) {
        String dateStr;
        if (idCard.length() == 15) {
            dateStr = "19" + idCard.substring(6, 12);
        } else if (idCard.length() == 18) {
            dateStr = idCard.substring(6, 14);
        } else {
            return -1;
        }
        System.out.println(dateStr);
        int age;
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);

        int year = Integer.parseInt(dateStr.substring(0, 4));
        int month = Integer.parseInt(dateStr.substring(4, 6));
        int day = Integer.parseInt(dateStr.substring(6));

        if ((month < monthNow) || (month == monthNow && day <= dayNow)) {
            age = yearNow - year;
        } else {
            age = yearNow - year - 1;
        }
        return age;
    }

    /**
     * 将list对象按照指定大小分割
     *
     * @param list      list数据
     * @param groupSize 每组数据大小
     * @param <T>
     * @return 分割后的list
     */
    public static <T> List<List<T>> splitList(List<T> list, int groupSize) {
        int length = list.size();
        // 计算可以分成多少组
        int num = (length + groupSize - 1) / groupSize; // TODO
        List<List<T>> newList = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            // 开始位置
            int fromIndex = i * groupSize;
            // 结束位置
            int toIndex = Math.min((i + 1) * groupSize, length);
            newList.add(list.subList(fromIndex, toIndex));
        }
        return newList;
    }

    /**
     * 根据数字获取中文大写
     *
     * @param nameCode 转换的数字
     * @return
     */
    public static String getChinaCode(String nameCode) {
        String[] numbers = nameCode.split("");
        StringBuilder num = new StringBuilder();
        for (String number : numbers) {
            switch (number) {
                case "1":
                    num.append("壹");
                    break;
                case "2":
                    num.append("贰");
                    break;
                case "3":
                    num.append("叁");
                    break;
                case "4":
                    num.append("肆");
                    break;
                case "5":
                    num.append("伍");
                    break;
                case "6":
                    num.append("陆");
                    break;
                case "7":
                    num.append("柒");
                    break;
                case "8":
                    num.append("捌");
                    break;
                case "9":
                    num.append("玖");
                    break;
                case "0":
                    num.append("零");
                    break;
                default:
                    break;
            }
        }
        return num.toString();
    }

    public static String chineseCode(String str) {
        final List<String> chinaNumbers = Arrays.asList("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾");

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int single = 0;
        for (String chinaNumber : chinaNumbers) {
            int index = str.indexOf(chinaNumber);
            int lastIndex = str.lastIndexOf(chinaNumber);

            if (index < min && index > -1) {
                single = index;
                final String substring = str.substring(index + 1, index + 2);
                if (chinaNumbers.contains(substring)) {
                    min = index;
                }
            }

            if (lastIndex > max && lastIndex > -1) {
                String substring = str.substring(lastIndex - 1, lastIndex);

                if (chinaNumbers.contains(substring)) {
                    max = lastIndex;
                } else {
                    for (int i = 1; i < lastIndex; i++) {
                        substring = str.substring(lastIndex - i, lastIndex - (i - 1));
                        if (chinaNumbers.contains(substring)) {
                            substring = str.substring(lastIndex - i - 1, lastIndex - i);
                            if (chinaNumbers.contains(substring)) {
                                max = lastIndex - i;
                                break;
                            }
                        }
                    }
                }
            }
        }
        String substring;
        if (min == Integer.MAX_VALUE && max == Integer.MIN_VALUE) {
            substring = str.substring(single, single + 1);
        } else {
            substring = str.substring(min, max + 1);
        }
        System.out.println(substring);
        return substring;
    }

    /**
     * 获取UUID，删除'-'后的字符
     *
     * @return
     */
    public static String randomUUID() {
        String ticket = UUID.randomUUID().toString();
        return ticket.replaceAll("-", "");
    }

    /**
     * 根据正则表达式获取匹配内容
     *
     * @param content 内容
     * @param regex   正则表达式
     * @return
     */
    public static String getMatchString(String content, String regex) {
        StringBuilder builder = new StringBuilder();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {
            builder.append(matcher.group(0)).append(";");
        }
        return builder.delete(builder.length() - 1, builder.length()).toString();
    }
}
